/**
 * 
 */
package org.teremail.message;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

import org.teremail.panto.BodyHeader;
import org.teremail.panto.ContentHandler;

class PrintContentHandler implements ContentHandler {
        
    private String pad = "";
    private int fieldCount = 0;
    private PrintStream out;
    
    public PrintContentHandler(PrintStream out) {
        this.out = out;
    }

    private void print(String string) {
        out.print(pad);
        out.println(string);
    }
    
    private int getLength(InputStream in) throws IOException {
        byte[] b = new byte[1024];
        int i = 0;
        int total = 0;
        while ((i = in.read(b)) != -1) {
            total += i;
        }
        return total;
    }

    public void body(BodyHeader header, InputStream is)
            throws IOException {
        print("body(" + getLength(is) + ")");                
    }

    public void endBodyPart() {
        pad = pad.substring(2);
        print("endBodyPart()");
    }

    public void endHeader() {
        print("field(" + fieldCount + ")");
        fieldCount = 0;
        pad = pad.substring(2);
        print("endHeader()");
    }

    public void endMessage() {
        pad = pad.substring(2);
        print("endMessage()");
    }

    public void endMultipart() {
        pad = pad.substring(2);
        print("endMultipart()");
    }

    public void epilogue(InputStream in) throws IOException {
        print("epilogue(" + getLength(in) + ")");
    }

    public void field(String fieldData) {
        //print("field()");
        fieldCount++;
    }

    public void preamble(InputStream in) throws IOException {
        print("preamble(" + getLength(in) + ")");
    }

    public void startBodyPart() {
        print("startBodyPart");
        pad = pad + "  ";
    }

    public void startHeader() {
        print("startHeader()");
        pad = pad + "  ";
    }

    public void startMessage() {
        print("startMessage()");
        pad = pad + "  ";
    }

    public void startMultipart(BodyHeader header) {
        print("startMultipart(" + header.getContentType() + ")");
        pad = pad + "  ";
    }
}